package model;
import java.util.Date;

import Repository.Repository;
import Repository.RepositoryFactory;
import constants.SMSConstants;

public class ImportRuleSelector implements RuleSelector{

	private Repository ruleRepository = RepositoryFactory.getRepository(SMSConstants.RULE);
	private SMSObject smsObject;
	
	public ImportRuleSelector(SMSObject smsObject){
		this.smsObject = smsObject;		
	}
	
	public boolean processRuleRequest(){
		//System.out.println("Processing Rule Request....");
		Rule importRule = getRule();
	//	System.out.println("Got rule.."+ importRule);
		return applyRule(importRule);
		
	}
	
	public Rule getRule() {
		
		//This if is for fetching import rules for lead.
		//We pass an SMS Object and check its type and state to find the rule to retrieve
		if(smsObject instanceof Lead && smsObject.getCurrentState() instanceof Raw){
			return  (Rule)ruleRepository.retrieve(SMSConstants.LEAD, SMSConstants.IMPORT);	
		}else // This is for fetching import rules for opportunity
			if(smsObject instanceof Lead && smsObject.getCurrentState() instanceof Qualified){
			return  (Rule)ruleRepository.retrieve(SMSConstants.OPPORTUNITY, SMSConstants.IMPORT);	
		}else // This is for fetching import rules for contract
			if(smsObject instanceof Opportunity ){
			return  (Rule)ruleRepository.retrieve(SMSConstants.CONTRACT, SMSConstants.IMPORT); 
		}
		return new NullRule();
	}
	
	private boolean applyRule(Rule rule){
		String criteria = rule.getRuleDescripton();
	//	System.out.println("Applying Rules...");
		if(smsObject instanceof Lead ){
			Lead objLead = (Lead)smsObject;
			if(smsObject.getCurrentState() instanceof Raw) {
				if(criteria.toLowerCase().equals("after june")){
					if(objLead.getLeadDate().getMonth() >= 5){
						return true;				
					}
			    }
		     }else if(smsObject.getCurrentState() instanceof Qualified){
		    	 if(criteria.toLowerCase().equals("dell laptop")){
		    		 if(objLead.getProductInterest().toLowerCase().contains("dell")){
							return true;				
						} 
		    	 }
		    	 
		     }
		} else if(smsObject instanceof Opportunity ){
			Opportunity objOpp = (Opportunity)smsObject;
			 if(criteria.toLowerCase().equals("closedate 30")){
				 Date todaysDate = new Date(System.currentTimeMillis());
				 Date closedDate = objOpp.getClosedDate();
				 long diff = (closedDate.getTime() - todaysDate.getTime())/(24*60*60*1000);
				// System.out.println("difference----"+diff);
				 if(diff<30){
					 return true;
				 }
				 
	    		 
	    	 }
			
		}
		
		return false;
	}

}
